﻿using Microsoft.SharePoint.WebControls;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CNRS.CCP.Connector;
using CNRS.CCP.Config;
using CNRS.CCP.DAO;
using Microsoft.SharePoint.Administration.Claims;

namespace CNRS.CCP.Connector
{
	public class SQLConnector
	{
		/// <summary>
		/// Search in a particular node RefList to found a match
		/// </summary>
		/// <param name="searchPattern"></param>
		/// <param name="node"></param>
		public static List<DataElement> GetDataElements(string searchPattern, ClaimElement element)
		{
			LogHelper.LogDebug(LogCategorie.SqlHelper, string.Format("SQl lookup for Claim : {0}", element.ClaimType));

			//string typeKey = element.Type + element.Key;
			//string nodeID = element.Key;
			//string nodeLabel = element.Title;
			//string nodeListRefName = element.DB; //table ou vue à utiliser
			//string nodeListRefID = element.ReferenceID; //Champs SQL à utiliser

			// set a null return Value
			List<DataElement> dataElements = null;

			if (!string.IsNullOrEmpty(searchPattern))
			{
				try
				{
					Provider provider = ClaimsParameters.Instance.SqlProvider;
					string connectionString = string.Format(provider.Server, provider.User, provider.Password);
					//string connectionString = string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", provider.Server, provider.Database, provider.User, provider.Password);
					//connectionString = string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password={3};", xmlNode["Server"].InnerText, xmlNode["Database"].InnerText, xmlNode["Login"].InnerText, SecurityHelper.ToInsecureString(SecurityHelper.DecryptString(xmlNode["SecuredPassword"].InnerText)).ToString());
					//string hiddenPasswordConnectionString = connectionString;// string.Format("Data Source={0};Initial Catalog={1};User Id={2};Password=XXXX;", xmlNode[Constantes.PARAMS_SQLSETTINGS_SERVER].InnerText, xmlNode[Constantes.PARAMS_SQLSETTINGS_DATABASE].InnerText, xmlNode[Constantes.PARAMS_SQLSETTINGS_LOGIN].InnerText);
					LogHelper.LogDebug(LogCategorie.SqlHelper, "CNRS Claims Parameters Login : " + connectionString);


					BaseDAO daoList = new BaseDAO(connectionString, element.DB);
					DAOParameter parameter = new DAOParameter() { Column = element.ReferenceID, ParameterName = "@" + element.ReferenceID, Value = searchPattern };

					LogHelper.LogDebug(LogCategorie.SqlHelper, string.Format("SQL query : from table '{0}' where '{1}' = '{2}'", element.DB, element.ReferenceID, searchPattern));
					dataElements = daoList.GetItems(parameter);
					LogHelper.LogDebug(LogCategorie.SqlHelper, string.Format("Elements returned -> '{0}'", dataElements.Count));
				}
				catch (Exception ex)
				{
					LogHelper.LogDebug(LogCategorie.SqlHelper, ex.Message);
				}
			}

			return dataElements;
		}



	}
}
